/*
 * @Author: 45F
 * @LastEditors: 45F
 * @Description: 业务方法
 * @Date: 2019-05-22 15:18:05
 * @LastEditTime: 2019-08-23 16:48:31
 */
import Cookies from 'js-cookie'
// cookie保存的天数
// import config from '@/config'
import { hasOneOf, objEqual } from '@/libs/tools'

export const TOKEN_KEY = 'sj_token'

export const setToken = (token) => {
  // Cookies.set(TOKEN_KEY, token, { expires: config.cookieExpires || 1 })
}

export const removeToken = () => {
  Cookies.remove(TOKEN_KEY)
}
// 市局
// export const getToken = (port) => {
//   const token = Cookies.get(TOKEN_KEY)
//   const oldPort = Cookies.get('port')
//   if (token && +oldPort === +port) return token
//   else return false
// }
export const getToken = () => {
  // debuggers
  const token = Cookies.get(TOKEN_KEY)
  if (token) {
    return token
  } else {
    return false
  }
}

export const setUser = user => {
  // Cookies.set('sj_user', user, { expires: config.cookieExpires || 1 })
}

export const removeUser = () => {
  Cookies.remove('sj_user')
}

export const getUser = () => {
  const user = Cookies.get('sj_user')
  if (user) return JSON.parse(user)
  else return false
}

export const setRoutes = routes => {
  sessionStorage.setItem('routes', JSON.stringify(routes))
}

export const removeRoutes = () => {
  sessionStorage.removeItem('routes')
}

export const getRoutes = () => {
  const routes = sessionStorage.getItem('routes')
  if (routes) return JSON.parse(routes)
  else return false
}

export const hasChild = item => {
  return item.children && item.children.length !== 0
}

/**
 * @param {Array} routeMetched 当前路由metched
 * @returns {Array}
 */
export const getBreadCrumbList = (route) => {
  let routeMetched = route.matched
  let res = routeMetched
    .filter(item => {
      return item.meta === undefined || !item.meta.hide
    })
    .map(item => {
      let meta = { ...item.meta }
      if (meta.title && typeof meta.title === 'function') meta.title = meta.title(route)
      let obj = {
        icon: (item.meta && item.meta.icon) || '',
        name: item.name,
        meta: meta
      }
      return obj
    })
  res = res.filter(item => {
    return !item.meta.hideInMenu
  })
  // return [Object.assign(homeRoute, { to: homeRoute.path }), ...res]
  return res
}

/**
 * @param {String} url
 * @description 从URL中解析参数
 */
export const getParams = url => {
  const keyValueArr = url.split('?')[1].split('&')
  let paramObj = {}
  keyValueArr.forEach(item => {
    const keyValue = item.split('=')
    paramObj[keyValue[0]] = keyValue[1]
  })
  return paramObj
}

/**
 * @param {Number} times 回调函数需要执行的次数
 * @param {Function} callback 回调函数
 */
export const doCustomTimes = (times, callback) => {
  let i = -1
  while (++i < times) {
    callback(i)
  }
}

/**
 * @param {Object} file 从上传组件得到的文件对象
 * @returns {Promise} resolve参数是解析后的二维数组
 * @description 从Csv文件中解析出表格，解析成二维数组
 */
export const getArrayFromFile = file => {
  let nameSplit = file.name.split('.')
  let format = nameSplit[nameSplit.length - 1]
  return new Promise((resolve, reject) => {
    let reader = new FileReader()
    reader.readAsText(file) // 以文本格式读取
    let arr = []
    reader.onload = function (evt) {
      let data = evt.target.result // 读到的数据
      let pasteData = data.trim()
      arr = pasteData
        .split(/[\n\u0085\u2028\u2029]|\r\n?/g)
        .map(row => {
          return row.split('\t')
        })
        .map(item => {
          return item[0].split(',')
        })
      if (format === 'csv') resolve(arr)
      else reject(new Error('[Format Error]:你上传的不是Csv文件'))
    }
  })
}

/**
 * @param {Array} array 表格数据二维数组
 * @returns {Object} { columns, tableData }
 * @description 从二维数组中获取表头和表格数据，将第一行作为表头，用于在iView的表格中展示数据
 */
export const getTableDataFromArray = array => {
  let columns = []
  let tableData = []
  if (array.length > 1) {
    let titles = array.shift()
    columns = titles.map(item => {
      return {
        title: item,
        key: item
      }
    })
    tableData = array.map(item => {
      let res = {}
      item.forEach((col, i) => {
        res[titles[i]] = col
      })
      return res
    })
  }
  return {
    columns,
    tableData
  }
}

export const findNodeUpper = (ele, tag) => {
  if (ele.parentNode) {
    if (ele.parentNode.tagName === tag.toUpperCase()) {
      return ele.parentNode
    } else {
      return findNodeUpper(ele.parentNode, tag)
    }
  }
}

export const findNodeUpperByClasses = (ele, classes) => {
  let parentNode = ele.parentNode
  if (parentNode) {
    let classList = parentNode.classList
    if (classList && classes.every(className => classList.contains(className))) {
      return parentNode
    } else {
      return findNodeUpperByClasses(parentNode, classes)
    }
  }
}

export const findNodeDownward = (ele, tag) => {
  const tagName = tag.toUpperCase()
  if (ele.childNodes.length) {
    let i = -1
    let len = ele.childNodes.length
    while (++i < len) {
      let child = ele.childNodes[i]
      if (child.tagName === tagName) return child
      else return findNodeDownward(child, tag)
    }
  }
}

export const showByAccess = (access, canViewAccess) => {
  return hasOneOf(canViewAccess, access)
}

/**
 * @description 根据name/params/query判断两个路由对象是否相等
 * @param {*} route1 路由对象
 * @param {*} route2 路由对象
 */
export const routeEqual = (route1, route2) => {
  const params1 = route1.params || {}
  const params2 = route2.params || {}
  const query1 = route1.query || {}
  const query2 = route2.query || {}
  return route1.name === route2.name && objEqual(params1, params2) && objEqual(query1, query2)
}

export const dateFormat = (obj, fmt) => {
  if (obj) {
    var o = {
      'M+': obj.getMonth() + 1, // 月份
      'd+': obj.getDate(), // 日
      'h+': obj.getHours(), // 小时
      'm+': obj.getMinutes(), // 分
      's+': obj.getSeconds(), // 秒
      'q+': Math.floor((obj.getMonth() + 3) / 3), // 季度
      S: obj.getMilliseconds() // 毫秒
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (obj.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (var k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
      }
    }
    return fmt
  } else {
    return ''
  }
}

export const convertDateFromString = (dateString, fmt) => {
  if (dateString) {
    if (fmt === 'yyyy-MM-dd' || fmt === 'yyyy-MM-dd hh:mm:ss') {
      return new Date(dateString.replace(/-/, '/'))
    } else {
      return null
    }
  } else {
    return null
  }
}

export const ObjectNone = object => {
  if (JSON.stringify(object) === '{}') return true
  else return false
}

/**
 * js导出xlsx文件
 * @param data {array} 表头描述;列标题，逗号隔开，每一个逗号(英文逗号)就是隔开一个单元格
 * @param columns {array} 表格内容;数组包含对象，每个对象单元为一个表格单元格
 * @param fileName {string} 表个名称
 */
export const jsExportXlsxFile = (columns = [], data = [], fileName = '数据表') => {
  let str = columns.join(',')
  str += `\n`
  // 增加\t为了不让表格显示科学计数法或者其他格式
  for (let i = 0; i < data.length; i++) {
    for (let item in data[i]) {
      str += `${data[i][item] + '\t'},`
    }
    str += '\n'
  }
  // encodeURIComponent解决中文乱码
  let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str)
  // 通过创建a标签实现
  let link = document.createElement('a')
  link.href = uri
  // 对下载的文件命名
  link.download = `${fileName}.csv`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
